package jp.sourceforge.akjrcp.imageedit;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import jp.sourceforge.akjrcp.flvtools.basic.OpenDirectable;
import jp.sourceforge.akjrcp.util.image.ImageUtils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.part.ViewPart;

/**
 * This sample class demonstrates how to plug-in a new workbench view. The view
 * shows data obtained from the model. The sample creates a dummy model on the
 * fly, but a real implementation would connect to the model available either in
 * this or another plug-in (e.g. the workspace). The view is connected to the
 * model using a content provider.
 * <p>
 * The view uses a label provider to define how model objects should be
 * presented in the view. Each view can present the same model objects using
 * different labels and icons, if needed. Alternatively, a single label provider
 * can be shared between views in order to ensure that objects of the same type
 * are presented in the same way everywhere.
 * <p>
 */

public class ImageListView extends AbstractImageListView{
	public static Log log = LogFactory.getLog(ImageListView.class);
	public static final String ID = ImageListView.class.getName();

	
	
	private String defaultDir=System.getProperty("user.home")+"/"+"My Documents/captures/";
	private String currentDir;
	private SelectAction selectAction=new SelectAction();
	
	private ImageButton currentButton;
	
	private String supprtedExtensions[]={"png","jpg","gif","bmp"};
	
	
	
	public ImageButton makeThumbnailButton(Composite parent,File file){
		
		Image base=new Image(null,file.getAbsolutePath());
		Image thumb=ImageUtils.createThumbnail(base,thumbnailWidth,thumbnailHeight);
		base.dispose();
		bufferImageCasher.putImage(thumb, file.getAbsolutePath());
		
		//Button bt=new Button(parent,SWT.NULL);
		//bt.setImage(bufferImageCasher.getImage(file.getAbsolutePath()));
		ImageButton bt=new ImageButton(parent,SWT.NULL,thumb.getBounds().width,thumb.getBounds().height);
		thumb.dispose();//no error.when disposed.
		bt.setImageName(file.getAbsolutePath());
		bt.setBufferImageCasher(bufferImageCasher);
		
		//bt.setImage(thumb);
		bt.setToolTipText(file.getName());
		bt.addSelectionListener(selectAction);
		log.info(bt.getBounds());
		return bt;
	}
	private BufferImageCasher bufferImageCasher=new BufferImageCasher();
	
	
	public class DirectoryChange implements SelectionListener{

		public void widgetDefaultSelected(SelectionEvent e) {
			
		}

		public void widgetSelected(SelectionEvent e) {
			CCombo combo=(CCombo) e.getSource();
			int index=combo.getSelectionIndex();
			if(index>=0){
				if(index==0){//re open
					doOpen(new File(currentDir).getAbsolutePath());
				}
				else if(index==1){//move up
					doOpen(new File(currentDir).getParent());
				}else{
					doOpen(new File(currentDir,combo.getItem(combo.getSelectionIndex())).getAbsolutePath());
				}
			}
			scrollComposite.setFocus();
		}
		
	}
	
	public class SelectAction implements SelectionListener{

		public void widgetDefaultSelected(SelectionEvent e) {
			
		}

		public void widgetSelected(SelectionEvent e) {
			if(currentButton!=null && !currentButton.isDisposed()){
				currentButton.setSelected(false);
				currentButton.redraw();
			}
			//System.out.println(e.getSource());
			
			ImageButton bt=(ImageButton) e.getSource();
			bt.setSelected(true);
			bt.redraw();
			currentButton=bt;
			File file=new File(currentDir,bt.getToolTipText());
			setSelection(new SelectFile(file));
			//getSite().getShell().setMinimized(true);nice work.
		}
		
	}
	public class OpenAction implements SelectionListener{

		public void widgetDefaultSelected(SelectionEvent e) {
			// TODO Auto-generated method stub
			
		}

		public void widgetSelected(SelectionEvent e) {
			doOpen();
		}
		
	}
	
	
	public void doOpen(){
		DirectoryDialog dialog=new DirectoryDialog(this.getSite().getShell());
		String path=dialog.open();
		if(path!=null){
			doOpen(path);
		}
	}
	
	private boolean isSupportedImage(String name){
		for (int i = 0; i < supprtedExtensions.length; i++) {
			if(name.toLowerCase().endsWith("."+supprtedExtensions[i])){
				return true;
			}
		}
		return false;
	}
	public void doOpen(String path){
		log.info("open:"+path);
		
		currentDir=path;
		directoryText.setText(path);
		bufferImageCasher.clear();
		//update combo
		if(directorySelect.getItemCount()>2){
			directorySelect.remove(2, directorySelect.getItemCount()-1);
		}
		//update image;
		Control controls[]=imageList.getChildren();
		System.out.println(controls.length);
		for (int i = 0; i < controls.length; i++) {
			controls[i].dispose();
		}
		
		imageList.update();
		/*
		try {
			Thread.sleep(10000);
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}*/
		//imageList.pack();
		
		int index=0;
		File dir=new File(path);
		File list[]=dir.listFiles();
		for (int i = 0; i < list.length; i++) {
			if(list[i].isDirectory()){
			directorySelect.add(list[i].getName());//add directory
			}else{
			if(isSupportedImage(list[i].getName())){//TODO support any images.
				try{
				log.info(list[i]);
				makeThumbnailButton(imageList,list[i]);
				index++;
				imageList.pack();
				imageList.update();//for paint
				log.info("index="+index);
				
				}catch(Exception e){
					
				}
			}
			}
		}
		imageList.layout();
			//imageList.getParent().layout();
		//imageList.layout();
		//imageList.pack();//very important!!
		//log.info(imageList.getBounds());
		//imageList.redraw();
		//imageList.pack();
		//imageList.layout();
		//imageList.update();
	}
	public void createPartControl(Composite root) {
		getSite().setSelectionProvider(this);
		
		root.setLayout(new GridLayout(1,false));
		
		directoryText = new Text(root,SWT.READ_ONLY);
		directoryText.setText("");
		GridData data1=new GridData(GridData.FILL_HORIZONTAL);
		directoryText.setLayoutData(data1);
		
		Button browse=new Button(root,SWT.NULL);
		browse.setText("open");
		browse.addSelectionListener(new OpenAction());
		
		directorySelect = new CCombo(root,SWT.READ_ONLY);
		directorySelect.add("");
		directorySelect.add("open parent");
		directorySelect.addSelectionListener(new DirectoryChange());
		
		
		
		scrollComposite = new ScrolledComposite(root,SWT.V_SCROLL);
		scrollComposite.getVerticalBar().setIncrement(10);
		//scrollComposite.addListener(SWT.MouseWheel, new WheelMove());
		
		scrollComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
		imageList = new Composite(scrollComposite,SWT.NULL);
		imageList.setLayout(new GridLayout(1,false));
		
		doOpen(defaultDir);//TODO:thread
		
		
		imageList.setSize(imageList.computeSize(SWT.DEFAULT, SWT.DEFAULT));//very important tips.
		scrollComposite.setContent(imageList);
		/*
		FigureCanvas canvas=new FigureCanvas(root);
		Panel panel=new Panel();
		canvas.setContents(panel);
		
		
		XYLayout layout=new XYLayout();
		
		panel.setLayoutManager(layout);
		
		RectangleFigure rect1=new RectangleFigure();
		rect1.setBackgroundColor(ColorConstants.green);
		
		panel.add(rect1,new Rectangle(10,10,30,30));
		RectangleFigure rect2 = new RectangleFigure();
        rect2.setBackgroundColor(ColorConstants.orange);
		panel.add(rect2,new Rectangle(100,100,30,30));
		*/
	}
	/*
	public class WheelMove implements Listener{

		public void handleEvent(Event event) {
			System.out.println(event);
		}
		
	}*/

	public class SelectFile implements ISelection{
		private File file;
		public SelectFile(File file){
			this.file=file;
		}
		public boolean isEmpty() {
			
			return false;
		}
		public File getFile() {
			return file;
		}
		public void setFile(File file) {
			this.file = file;
		}
		
	}
	/**
	 * Passing the focus request to the viewer's control.
	 */
	public void setFocus() {
		//doOpen(defaultDir);
		scrollComposite.setFocus();
	}



	List  listeners=new ArrayList();
	ISelection current;

	private Text directoryText;

	private Composite imageList;

	private CCombo directorySelect;

	private ScrolledComposite scrollComposite;
	public void addSelectionChangedListener(ISelectionChangedListener listener) {
		listeners.add(listener);
	}



	public ISelection getSelection() {
		
		return current;
	}



	public void removeSelectionChangedListener(ISelectionChangedListener listener) {
		listeners.remove(listener);
	}



	public void setSelection(ISelection selection) {
		log.info("setSelection");
		current=selection;
		Iterator iterator=listeners.listIterator();
		SelectionChangedEvent event=new SelectionChangedEvent(this,selection);
		while(iterator.hasNext()){
			ISelectionChangedListener listener=(ISelectionChangedListener)iterator.next();
			listener.selectionChanged(event);
		}
	}

}